package com.qriver.distributedlock.controller;

import com.qriver.distributedlock.config.ZookeeperConfig;
import com.qriver.distributedlock.lock.ZookeeperLock;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@RestController
public class DemoController {

    private Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private ZookeeperConfig zookeeperConfig;

    @Autowired
    private CuratorFramework curatorFramework;

    @RequestMapping("curatorLock")
    public String curatorLock() {
        logger.debug("curatorLock()方法；");
        InterProcessMutex lock = new InterProcessMutex(curatorFramework,"/order");
        try{
            if(lock.acquire(30, TimeUnit.SECONDS)){
                logger.debug("获取到锁；");
                Thread.sleep(20 * 1000);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            logger.debug("释放锁；");
            try {
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        logger.debug("方法执行完成；");
        return "方法执行完成";
    }

    @RequestMapping("zkLock")
    public String testLock() {
        logger.debug("进入testLock()方法；");
        //“order"表示业务模块
        try(ZookeeperLock lock = new ZookeeperLock(zookeeperConfig)){
            if(lock.getLock("order")){
                logger.debug("获取到锁；");
                Thread.sleep(20 * 1000);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        logger.debug("方法执行完成；");
        return "方法执行完成";
    }

}
